package org.acme.cluster.service;

import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.Receiver;
import org.jgroups.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SysClusterServiceImpl implements SysClusterService, CommandLineRunner, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    private UUID uuid;

    private JChannel channel;

    @Resource
    private SysSmsDispatchService sysSmsDispatchService;

    @Resource
    private SysSmsService sysSmsService;

    @Override
    public void destroy() throws Exception {
        this.stopChannel();
    }

    @Override
    public void startChannel() throws Exception {
        this.channel = new JChannel("jgroups-udp.xml");
        this.channel.setReceiver((Receiver) sysSmsDispatchService);
        this.channel.connect(DEFAULT);
        this.uuid = (UUID) this.channel.getAddress();
        if (this.channel.getView().getMembers().size() == 1) {
            this.sysSmsService.updateAllSmsServerKey(this.uuid.toStringLong());
        }
        logger.warn("服务节点: {} 启动完毕 ...", this.uuid.toStringLong());
    }

    @Override
    public void stopChannel() throws Exception {
        if (this.channel != null) {
            this.channel.disconnect();
            this.channel.close();
        }
    }

    /***
     * 当前节点id
     * @return
     */
    @Override
    public UUID getUuid() {
        return this.uuid;
    }

    /****
     * 广播消息
     * @param message
     * @throws Exception
     */
    @Override
    public void sendAll(Object message) throws Exception {
        this.channel.send(null, message);
    }

    /****
     * 单发消息
     * @param address
     * @param message
     * @throws Exception
     */
    @Override
    public void sendTo(Address address, Object message) throws Exception {
        this.channel.send(address, message);
    }

    /***
     * 启动服务节点
     * @param args incoming main method arguments
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        this.startChannel();
    }
}
